package work.mediway.mdm.core.util;

import java.util.Date;
import java.util.List;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

/**
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2020/4/16
 */
public class CodeGenerateUtil {

    public static final int DEFAULT_LEN = 6;

    public static final int DEFAULT_RANDOM_LEN = 4;

    public static final int DEFAULT_RANDOM_MIN_LEN = 3;

    public static final char DEFAULT_FILL_CHAR = '0';

    public static String code(String prefix) {
        return prefix + StrUtil.fillBefore(random(), DEFAULT_FILL_CHAR, DEFAULT_LEN);
    }

    public static String code(String prefix, int len) {
        return prefix + StrUtil.fillBefore(random(), DEFAULT_FILL_CHAR, len);
    }

    public static String code(String prefix, Character c) {
        return prefix + StrUtil.fillBefore(random(c, DEFAULT_LEN), c, DEFAULT_LEN);
    }

    public static String code(String prefix, Character c, int len) {
        return prefix + StrUtil.fillBefore(random(c, len), c, DEFAULT_LEN);
    }

    private static String random() {
        return random(DEFAULT_FILL_CHAR, DEFAULT_RANDOM_LEN);
    }

    private static String random(Character c, int len) {
        len = Math.min(len, DEFAULT_LEN);
        len = Math.max(len, DEFAULT_RANDOM_MIN_LEN);
        String format = DateUtil.format(new Date(), DatePattern.NORM_DATETIME_MS_PATTERN);
        String time = StrUtil.splitToArray(format, StrUtil.SPACE)[1];
        List<String> timeSplit = StrUtil.split(time, StrUtil.C_COLON);
        return StrUtil.fillBefore(timeSplit.get(timeSplit.size() - 1), c, len);
    }

}

